package org.urchr.beorganized.api.base;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.postgresql.util.Base64;
import org.urchr.beorganized.dao.UsersDAO;
import org.urchr.beorganized.dao.errors.GeneralException;
import org.urchr.beorganized.dao.errors.NoPermissionException;
import org.urchr.beorganized.dao.tables.User;

abstract public class PrivateBaseAPIServlet extends BaseAPIServlet{

	private static Map<String, Integer> sessions = new HashMap<String, Integer>();
	
	public static void clearSession(int user){
		
	}
	
	public static int checkToken(String token){
		Integer res = sessions.get(token);
		if(res!=null)
			return res.intValue();
		
		String decoded = new String(Base64.decode(token));
//		System.out.println("Decoded = "+decoded);
		String login = decoded.substring(0, decoded.indexOf("@"));
//		System.out.println("Login = "+login);
		String pass = decoded.substring(decoded.indexOf("@")+1);
		
		try {
			User user = UsersDAO.authorizeUser(login, pass, true);
			sessions.put(token, user.getId());
			return user.getId();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return -1;
	}
	
	protected int userID = 0;
	protected String login = null;
	
	@Override
	protected void doProcess() throws GeneralException {
		String token = getParameter("token");
		if(token==null)
			throw new NoPermissionException();
		try {
			userID = checkToken(token);
			if(userID==-1)
				throw new NoPermissionException();
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoPermissionException();
		}
//		System.out.println("login: "+login+", userID = "+userID);
		doProcessPrivate();
	}
	
	abstract protected void doProcessPrivate() throws GeneralException;
	
}
